/*
 * Copyright (c) 2008-2014, RF-Embedded GmbH
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 *  1. Redistributions of source code must retain the above copyright notice, 
 *     this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright notice, 
 *     this list of conditions and the following disclaimer in the 
 *     documentation and/or other materials provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
 * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR 
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.rfe.protocol;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import com.rfe.JrfeGlobal;
import com.rfe.helper.JrfeHelper;

/**
 * Class to store recieved messages.
 */
public class JrfeMessageQueue {
	/**
	 * The stored messages
	 */
	private Hashtable<Integer, ArrayList<byte[]>> m_messageQueue = new Hashtable<Integer, ArrayList<byte[]>>();
	
	/**
	 * Constructs a new message queue
	 */
	public JrfeMessageQueue()
	{
		m_messageQueue.clear();
	}
	
	/**
     * Enqueues the given message with the given id. If a message with this id is already present, it is replaced.
     * @param id  		Message id
     * @param message 	Message
     */
    public void enqueueMessage(int id, byte[] message)
    {
    	synchronized(m_messageQueue)
    	{
	    	ArrayList<byte[]> list;
	        if (!m_messageQueue.containsKey(id))
	            m_messageQueue.put(id, new ArrayList<byte[]>());
	        list = (ArrayList<byte[]>) m_messageQueue.get(id);
	        list.add(message);
	        JrfeGlobal.trc(8, "IN [" + Integer.toHexString(id) + "] " + JrfeHelper.toHexString(message));
    	}
    	
    }

    /**
     * Waits for a message with the given message id for the given time.
     * @param id 	Message id to wait for
     * @param msecs	Maximum time to wait for the message
     * @param ok 	Result of the waiting
     * @returns 	The message, if the operation did not succeed, null is returned.
	 */
    public byte[] waitForMessage(int id, int msecs, AtomicBoolean ok)
    {
    	int i = 0;
        int cycles = msecs / 10;

        ok.set(false);

        byte[] ret = null;
        List<byte[]> list = null;

        // check for the flag for the given time
        while(i++ < cycles)
        {
        	synchronized (m_messageQueue) 
        	{
	            if (list == null)
	            {
	                list = m_messageQueue.get(id);
	            }
	            if (list != null)
	            {
	                if(list.size() > 0)
	                {
	                    ret = new byte[list.get(0).length];
	                    System.arraycopy(list.get(0), 0, ret, 0, ret.length);
	                    list.remove(0);
	                    if (list.size() == 0)
	                        m_messageQueue.remove(id);
	                    ok.set(true);
	                }
	            }
			}

            if (ok.get() == true)
                break;

            try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
        }

        return ret;
    }
    
    /**
     * Clears all messages from the given id
     * @param id	ID of the message
     */
    public void clearMessage(int id)
    {
    	synchronized (m_messageQueue) {
    		m_messageQueue.remove(id);
    	}
    }

	
}
